<!-- 网络请求 -->
<template>
	<view class="page-demo-request">
		<cu-custom  bgColor="bgcolor-main"  :isCustom="true" :isBack="true">
			<view slot="content" >网络请求</view>
		</cu-custom>
		<view @click="request('GET')"   class="btn-main inline">GET请求</view>
		<view @click="request('POST')" class="btn-main inline">POST请求</view>
		<view @click="choose"  class="btn-main inline">选择图片</view>
		<view @click="upload"  class="btn-main inline">批量上传</view>
		<view @click="chooseUpload"  class="btn-main inline">单个上传</view>
	</view>
</template>

<script>
export default {
	data() {
		return { 
			options:{},
			upload_local:[],
			upload_success:[],
		}
	}, 
	onLoad(options) {
		this.options=options;
	},
	onShareAppMessage(res){
		return {
			title: '',
			path:"/pages/index/index"
		}
	},
	onShow(){},
	onReachBottom(){},
	onHide(){}, 
	onReady(){},
	methods: {
		request:function(method){
			var _this=this;
			this.$api.request({
				url:"/api/goods/search",
				//url也可以是完整链接，如：https://demo.com/api/xxxx
				method:method,
				data:{page:1,per_page:20,keyword:"便宜"},
				success:function(res){
					if(res.code==200){
						//数据渲染
					}else{
						_this.$toast(res.msg)
					}
				},
				fail:function(err){
					_this.$toast("请求出错");
					console.log("请求出错",err);
				}
			})
		},
		choose:function(){
			var _this=this;
			uni.chooseImage({
				count:3,
				success:function(res){
					_this.upload_local=res.tempFilePaths;
				}
			})
		},
		upload:function(){
			//批量上传
			var _this=this;
			if(this.upload_local.length<1)return false;
			this.$showLoading("上传中");
			for(var i in this.upload_local){ 
				console.log(this.upload_local[i])
				_this.$api.upload({
					url:"/api/attachment/upload",
					path:this.upload_local[i],//本地文件路径
					name:"file",//文件的表单字段名称
					data:{dir:"images"},//自定义表单数据,
					success:function(res){
						if(res.code==200){
							//将上传后的路径保存，并进行下一步
							_this.upload_success.push(res.data.path);
							if(_this.upload_local.length==_this.upload_success){
								_this.$hideLoading();
								//上传完成, 进行下一步操作
								
							}
						}else{ 
							_this.$hideLoading();
							//上传异常处理
							
						}
					},
					fail:function(err){
						_this.$hideLoading();
					}
				})
			}
		},
		chooseUpload:function(){
			var _this=this; 
			uni.chooseImage({
				count:1,
				success:function(res){
					_this.$api.upload({
						url:"/api/attachment/upload",
						path:res.tempFilePaths[0],//本地文件路径
						name:"file",//文件的表单字段名称
						data:{dir:"images"},//自定义表单数据,
						success:function(res){
							if(res.code==200){
								
							}else{
								
							}
						},
						fail:function(err){
							
						}
					})
				}
			})
		}
	}
}
</script>

<style lang="scss">
	.page-demo-request{ 
		text-align: left;
		.btn-main{
			width:40vw ;
			margin:30upx 5vw;
		}
	}
</style>
